﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using PeiYue.Common.HttpContextUser;
using PeiYue.IServices.Store;
using PeiYue.Model;
using PeiYue.Model.Dto.Purchase;
using PeiYue.Model.Dto.Store;
using PeiYue.Model.Models.Store;

namespace PeiYue.Api.Controllers.Store
{
    /// <summary>
    /// 扫码收货
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    //[Authorize(Permissions.Name)] 
    [Authorize]
    public class ReceiptController : ControllerBase
    {
        readonly IUser _user;
        readonly IMapper _mapper;
        readonly IReceiptServices _receiptServices;
        readonly IReceiptRecordServices _receiptRecordServices;
        readonly IStoreSortingLogServices _storeSortingLogServices;

        public ReceiptController(IReceiptServices receiptServices, IReceiptRecordServices receiptRecordServices, IStoreSortingLogServices storeSortingLogServices
           , IUser user, IMapper mapper)
        {
            _user = user;
            _receiptServices = receiptServices;
            _receiptRecordServices = receiptRecordServices;
            _storeSortingLogServices = storeSortingLogServices;
            this._mapper = mapper;
        }

        /// <summary>
        /// 获取需要收货列表
        /// </summary>
        /// <param name="querymodel"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<PageModel<ERPPurchaseDetailDTO>>> GetSpuReceipt([FromQuery] SearchERPPurchaseDetailDTO querymodel)
        {
            List<ERPPurchaseDetailDTO> dto = new List<ERPPurchaseDetailDTO>();
            var list = await _receiptServices.GetSpuReceipt(querymodel);
            if (list.Count > 0)
            {
                if (!string.IsNullOrEmpty(querymodel.BarCode) || !string.IsNullOrEmpty(querymodel.SupplierCode))
                    dto = _mapper.Map<List<ERPPurchaseDetailDTO>>(list);
                else
                {
                    //if(!string.IsNullOrEmpty(querymodel.SupplierCode)) querymodel.

                    dto = list.GroupBy(i => new { i.SupplierCode, i.SupplierName }).Select(i => new ERPPurchaseDetailDTO()
                    { SupplierCode = i.Key.SupplierCode, SupplierName = i.Key.SupplierName, Qty = i.Count(), ReceiptQty = i.Count(j => j.Id > 0), Flag = (i.Any(f => f.Id == 0) ? 0 : 1) }).ToList();//PackQty = i.Sum(c => c.PackQty) ,, Flag = (i.Any(f => f.Flag == 0) ? 0 : 1) }
                }
            }
            return new MessageModel<PageModel<ERPPurchaseDetailDTO>>()
            { msg = "获取成功", success = true, response = new PageModel<ERPPurchaseDetailDTO>() { data = dto } };
            //{ msg = dto.Count()>0? "获取成功" : "无数据", status=dto.Count()>0?200:209, success = true, response = new PageModel<ERPPurchaseDetailDTO>() { data = dto } };
        }
        /// <summary>
        /// 提交收货
        /// </summary>
        /// <param name="models"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<string>> SetReceipt([FromBody] List<ReceiptRecord> models)
        {
            var data = new MessageModel<string>();
            data.success = await _receiptRecordServices.SetReceiptRecords(models);
            if (!data.success) data.status = 500; else data.msg = "提交成功!";
            return data;
        }


        /// <summary>
        /// 扫码收货
        /// </summary>
        /// <param name="models"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<ERPPurchaseDetailDTO>> ScanReceipt([FromBody] ScanBarCode barCode)
        {
            var data = new MessageModel<ERPPurchaseDetailDTO>();
            try
            {
                //if (_user.ID == 0)
                //{
                //    data.success = false;
                //    data.status = 401;
                //    data.msg = "很抱歉，您无权访问该接口，请确保已经登录!";
                //    return data;
                //}
                if (string.IsNullOrEmpty(barCode.BarCode) || barCode.BarCode.Length < 9)
                { data.status = 500; data.msg = "无效条码"; return data; }

                var receipt = (await _receiptServices.GetSpuReceipt(new SearchERPPurchaseDetailDTO() { ScanCode = barCode.BarCode }))?.FirstOrDefault();
                if (receipt != null)
                {
                    if (receipt.UpdateUser > 0)
                    { data.status = 300; data.msg = "已收货"; return data; }
                    List<ReceiptRecord> record = new List<ReceiptRecord>();

                    record.Add(new ReceiptRecord() { BarCode = receipt.BarCode, UpdateUser = _user.ID, FID = receipt.fID, ReceiptQty = receipt.AnswerQty, CustomerCode = receipt.CustomerCode, SupplierCode = receipt.SupplierCode, SkuCode = receipt.SkuCode });

                    data.success = await _receiptRecordServices.SetReceiptRecords(record);
                    if (!data.success) data.status = 500;
                    else
                    {
                        //receipt = (await _receiptServices.GetSpuReceipt(new SearchERPPurchaseDetailDTO() { ScanCode = barCode.BarCode }))?.FirstOrDefault();
                        receipt.ReceiptQty = receipt.AnswerQty;
                        receipt.ReceiptUser = _user.Namec;
                        receipt.ScanDate = DateTime.Now;
                        data.response = _mapper.Map<ERPPurchaseDetailDTO>(receipt);
                        data.msg = "收货成功!";
                    }
                }
                else
                {
                    data.status = 500;
                    data.msg = "条码匹配错误!";//$( { barCode?.BarCode} )
                    //记录错误条码
                    Common.LogHelper.SerilogServer.WriteLog("ScanReceipt" + DateTime.Now.ToString("yyyyMMdd"), new string[] { barCode?.BarCode });
                }
            }
            catch (Exception ex)
            {
                Common.LogHelper.SerilogServer.WriteErrorLog("ScanReceiptError" + DateTime.Now.ToString("yyyyMMdd"), "扫码收货错误", ex);
            }

            return data;
        }

        /// <summary>
        /// 撤销收货
        /// </summary>
        /// <param name="models"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<string>> ReturnReceipt([FromBody] ScanBarCode barCode)
        {
            var data = new MessageModel<string>();
            if (_user.ID == 0)
            {
                data.success = false;
                data.status = 401;
                data.msg = "很抱歉，您无权访问该接口，请确保已经登录!";
                return data;
            }
            if (string.IsNullOrEmpty(barCode.BarCode) || barCode.BarCode.Length < 9)
            { data.status = 500; data.msg = "无效条码"; return data; }
            var models = await _receiptRecordServices.Query(i => i.BarCode == barCode.BarCode && i.Status == 1);
            if (models.Count > 0)
            {
                models.ForEach(i => i.Status = 0);
                data.success = await _receiptRecordServices.Update(models);
                data.msg = "撤销成功!";
            }
            else { data.status = 300; data.msg = "已不存在!"; }
            return data;
        }


        /// <summary>
        /// 获取收货记录
        /// </summary>
        /// <param name="models"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<List<ERPPurchaseDetailDTO>>> GetReceiptLog()
        {
            var data = new MessageModel<List<ERPPurchaseDetailDTO>>();
            var receipt = await _receiptServices.GetSpuReceipt(new SearchERPPurchaseDetailDTO() { ScanUser = _user.ID });
            if (receipt != null)
            {
                if (receipt.Count > 30)
                {
                    data.response = _mapper.Map<List<ERPPurchaseDetailDTO>>(receipt.OrderByDescending(p => p.ScanDate.Value).Take(30));
                }
                else
                {
                    data.response = _mapper.Map<List<ERPPurchaseDetailDTO>>(receipt);
                }
                data.response = data.response.OrderByDescending(o => o.ScanDate).ToList();
                data.msg = "获取成功!";
            }
            return data;
        }


        /// <summary>
        /// 收货缺货
        /// </summary>
        /// <param name="models"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<ERPPurchaseDetailDTO>> ShortageReceipt([FromBody] ScanBarCode barCode)
        {
            var data = new MessageModel<ERPPurchaseDetailDTO>();
            if (_user.ID == 0)
            {
                data.success = false;
                data.status = 401;
                data.msg = "很抱歉，您无权访问该接口，请确保已经登录!";
                return data;
            }
            if (string.IsNullOrEmpty(barCode.BarCode) || barCode.BarCode.Length < 9)
            { data.status = 500; data.msg = "无效条码"; return data; }
            var receipt = (await _receiptServices.GetSpuReceipt(new SearchERPPurchaseDetailDTO() { ScanCode = barCode.BarCode }))?.FirstOrDefault();
            if (receipt != null)
            {
                List<ReceiptRecord> record = new List<ReceiptRecord>();

                record.Add(new ReceiptRecord() { BarCode = receipt.BarCode, UserName = _user.Namec, UpdateUser = _user.ID, FID = receipt.fID, ReceiptQty = 0, CustomerCode = receipt.CustomerCode, SupplierCode = receipt.SupplierCode, SkuCode = receipt.SkuCode });

                data.success = await _receiptRecordServices.SetReceiptRecords(record);
                if (!data.success) data.status = 500;
                else
                {
                    //receipt = (await _receiptServices.GetSpuReceipt(new SearchERPPurchaseDetailDTO() { ScanCode = barCode.BarCode }))?.FirstOrDefault();
                    receipt.ReceiptQty = 0;
                    data.response = _mapper.Map<ERPPurchaseDetailDTO>(receipt);
                    data.msg = "提交成功!";
                }
            }
            else { data.status = 300; data.msg = "提交失败!"; }

            return data;
        }


    }
}
